﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ThinhTien.Models;

using DevExpress.Web.Mvc;
using DevExpress.Data;
using DevExpress.Data.Filtering;
using DevExpress.Data.Linq;
using DevExpress.Data.Linq.Helpers;
using ThinhTien.EF4;

namespace ThinhTien.Data
{
    public class ProductRepository : BaseRepository<ProductRepository>
    {
        public void AddNew(ProductViewModel model, List<ImageViewModel> images)
        {
            try
            {
                using (var db = new THINHTIENDBEntities())
                {
                    var productID = (from item in db.Products
                                     orderby item.ID descending
                                     select item.ID).FirstOrDefault() + 1;

                    db.Products.Add(new Product()
                    {
                        ID = productID,
                        CategoryID = model.CategoryID,
                        Description = model.Description,
                        DescriptionDetail = model.DescriptionDetail,
                        Name = model.Name,
                        Price = model.Price,
                        Warranty = model.Warranty,
                        CreatedBy = model.UserID,
                        UpdatedBy = model.UserID,
                        CreatedDate = DateTime.Now,
                        UpdatedDate = DateTime.Now,
                        IsDeleted = false
                    });

                    foreach (var item in images)
                    {
                        var imageID = Guid.NewGuid();
                        db.Images.Add(new Image()
                        {
                            ID = imageID,
                            Filename = item.Filename,
                            Size = item.FileSize,
                            Image1 = item.FileData
                        });

                        db.ProductImages.Add(new ProductImage()
                        {
                            ID = Guid.NewGuid(),
                            ImageID = imageID,
                            ProductID = productID
                        });
                    }


                    db.SaveChanges();
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        public void Update(ProductViewModel model, List<ImageViewModel> images)
        {
            try
            {
                using (var db = new THINHTIENDBEntities())
                {
                    if (model.ProductImages != null)
                    {
                        foreach (var item in model.ProductImages)
                        {
                            if (item.IsDeleted)
                            {
                                var productImages = (from productImage in db.ProductImages
                                                     where productImage.ImageID == item.ID
                                                     select productImage).ToList();

                                foreach (var productImage in productImages)
                                {
                                    db.ProductImages.Remove(productImage);
                                }

                                var images_ = (from image in db.Images
                                               where image.ID == item.ID
                                               select image).ToList();

                                foreach (var image in images_)
                                {
                                    db.Images.Remove(image);
                                }
                            }
                        }
                    }

                    var product = (from item in db.Products
                                   where item.ID == model.ProductID
                                   select item).FirstOrDefault();

                    if (product != null)
                    {
                        product.CategoryID = model.CategoryID;
                        product.Description = model.Description;
                        product.DescriptionDetail = model.DescriptionDetail;
                        product.Name = model.Name;
                        product.Price = model.Price;
                        product.Warranty = model.Warranty;
                        product.UpdatedBy = model.UserID;
                        product.UpdatedDate = DateTime.Now;

                        foreach (var item in images)
                        {
                            var imageID = Guid.NewGuid();
                            db.Images.Add(new Image()
                            {
                                ID = imageID,
                                Filename = item.Filename,
                                Size = item.FileSize,
                                Image1 = item.FileData
                            });

                            db.ProductImages.Add(new ProductImage()
                            {
                                ID = Guid.NewGuid(),
                                ImageID = imageID,
                                ProductID = model.ProductID
                            });
                        }

                        db.SaveChanges();
                    }
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        public void Delete(List<int> ids)
        {
            try
            {
                using (var db = new THINHTIENDBEntities())
                {
                    var product = (from item in db.Products
                                   where ids.Contains(item.ID)
                                   select item).ToList();

                    foreach (var pro in product)
                    {
                        db.Products.Remove(pro);
                    }

                    db.SaveChanges();
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        public ProductViewModel GetProductById(int id)
        {
            var product = (from item in Database.DbInstant.Products
                           where item.ID == id
                           select new ProductViewModel()
                           {
                               ProductID = item.ID,
                               Name = item.Name,
                               Price = item.Price,
                               Description = item.Description,
                               DescriptionDetail = item.DescriptionDetail,
                               Warranty = item.Warranty
                           }).FirstOrDefault();

            product.ProductImages = (from productImage in Database.DbInstant.ProductImages
                                     join image in Database.DbInstant.Images on productImage.ImageID equals image.ID
                                     where productImage.ProductID == id
                                     select new ImageViewModel()
                                     {
                                         ID = image.ID,
                                         Filename = image.Filename,
                                         FileData = image.Image1,
                                         FileSize = image.Size
                                     }).ToList();

            return product;
        }
    }

    public static class ProductBindingHandler
    {
        public static void GetDataRowCount(GridViewCustomBindingGetDataRowCountArgs e)
        {
            using (var db = new THINHTIENDBEntities())
            {
                e.DataRowCount = (from product in db.Products
                                  select product).ApplyFilter(e.FilterExpression).Count();
            }
        }

        public static void GetData(GridViewCustomBindingGetDataArgs e)
        {
            using (var db = new THINHTIENDBEntities())
            {
                var query = (from product in db.Products
                             join user in db.Users on product.UpdatedBy equals user.ID
                             select new
                             {
                                 product.CategoryID,
                                 product.CreatedBy,
                                 product.CreatedDate,
                                 product.Description,
                                 product.DescriptionDetail,
                                 product.ID,
                                 product.IsDeleted,
                                 product.Name,
                                 product.Price,
                                 product.UpdatedDate,
                                 product.Viewing,
                                 product.Warranty,
                                 user.UserName
                             }).Distinct().OrderByDescending(p => p.UpdatedDate)
                            .ApplySorting(e.State.SortedColumns)
                            .ApplyFilter(e.State.FilterExpression)
                            .Skip(e.StartDataRowIndex).Take(e.DataRowCount);

                List<ProductViewModel> data = new List<ProductViewModel>();
                foreach (dynamic item in query)
                {
                    data.Add(new ProductViewModel()
                    {
                        ProductID = item.ID,
                        CategoryID = item.CategoryID,
                        Description = item.Description,
                        DescriptionDetail = item.DescriptionDetail,
                        IsDeleted = item.IsDeleted,
                        Name = item.Name,
                        Price = item.Price,
                        UpdatedBy = item.UserName,
                        UpdatedDate = item.UpdatedDate,
                        Viewing = item.Viewing,
                        Warranty = item.Warranty
                    });
                }

                if (data.Count == 0)
                {
                    data.Add(new ProductViewModel()
                    {
                        ProductID = 0
                    });
                }

                e.Data = data;
            }
        }
    }
}
